﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web;
using System.Web.Mvc;

namespace GoDive.Common
{
    public class BaseController : Controller
    {

        private Dictionary<string, string> _where = null;
        
        public int PageIndex
        {
            get { return this.GetFormValue<int>("page", 1); }
        }

        public int PageSize
        {
            get { return this.GetFormValue<int>("pagesize"); }
        }

        public string this[string key]
        {
            get
            {
                if (_where==null)
                {
                    _where = this.GetWhere();
                }

                if (_where.ContainsKey(key))
                {
                    return _where[key];
                }
                return null;
            }
        }

        private Dictionary<string, string> GetWhere()
        {
            if (_where != null)
            {
                return _where;
            }

            _where = new Dictionary<string, string>();
            string where = this.GetFormValue<string>("where");
            if (!string.IsNullOrEmpty(where))
            {
                string[] arr = where.Split(new char[] { '&' }, StringSplitOptions.RemoveEmptyEntries);
                for (int i = 0; i < arr.Length; i++)
                {
                    string[] keyvalue = arr[i].Split('=');
                    if (keyvalue.Length != 2)
                    {
                        continue;
                    }
                    if (!_where.ContainsKey(keyvalue[0]))
                    {
                        _where.Add(keyvalue[0], HttpUtility.UrlDecode(keyvalue[1]));
                    }
                }
            }

            return _where;
        }


        public T GetFormValue<T>(string key, T defaultValue = default(T))
        {
            if (string.IsNullOrEmpty(Request.Form[key]))
            {
                return defaultValue;
            }

            try
            {
                return (T)Convert.ChangeType(Request.Form[key], typeof(T));
            }
            catch
            {
                return defaultValue;
            }
        }

    }
}
